#!/usr/bin/env gosh
(use srfi-1)
(use util.match)
(use file.util)
(use gauche.sequence)

(define-macro (aif test-form then-form . else-form)
  `(let ((it ,test-form))
     (if it ,then-form ,@else-form)))

(define (extract-quasiquote-vector obj)
  (match obj
  (('define (name . args) ('quasiquote #(pat ...)))
   `(define (,name ,@args)
      (let1 v (make-vector ,(length pat))
        ,@(map-with-index
           (lambda (i x)
             `(vector-set! v ,i ,(if (pair? x) (second x) x)))
           pat)
        v)))
  (else
   obj)))

(define (write-pre-cond body)
  (for-each
   (lambda (x)
     (match x
       [('include file-name)
        (for-each write (file->sexp-list file-name))]
       [else (write x)]))
   body))


(define (main args)
  (format #t ";; Do not edit this file generated by ~a.\n" (first args))
  (with-input-from-file (second args)
    (lambda ()
      (let loop ([obj (read)])
        (cond
         [(eof-object? obj) '()]
         [else
          (match obj
            [('pre-cond . body)
             (aif (find (lambda (x) (eq? (car x) (string->symbol (third args)))) body)
                  (write-pre-cond (cdr it))
                  (errorf "condition? ~a not found " (third args)))]
            [else (write (extract-quasiquote-vector obj))])
          (loop (read))]))))
  0)

;; (define (main args)
;;   (format #t ";; Do not edit this file generated by ~a.\n" (first args))
;;   (with-input-from-file (second args)
;;     (lambda ()
;;       (let loop ([obj (read)])
;;         (cond
;;          [(eof-object? obj) '()]
;;          [else
;;           (if (and (pair? obj) (eq? 'pre-cond (first obj)))
;;               (begin
;;                 (for-each write  (cdr (find (lambda (x) (eq? (car x) (string->symbol (third args)))) (cdr obj)))))
;;               (write (extract-quasiquote-vector obj)))
;;           (loop (read))]))))
;;   0)
